package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询，参数：{}",dishPageQueryDTO);
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }
    @PostMapping("/status/{status}")
    @ApiOperation("菜品启售禁售")
    public Result startOrStop(@PathVariable Integer status,Long id){
        dishService.sos(status,id);
        cleanRedis("dish_*");//清楚菜品缓存
        return Result.success();
    }
    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO){
        dishService.addDish(dishDTO);
        cleanRedis("dish_"+dishDTO.getCategoryId());//清楚菜品缓存
        return Result.success();
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishDTO> getDish(@PathVariable Long id){
        log.info("查询id为{}的菜品",id);
        DishDTO dishDTO = dishService.getDish(id);
        return Result.success(dishDTO);
    }
    @DeleteMapping()
    @ApiOperation("删除商品")
    public Result deleteDish(String ids){
        dishService.deleteDish(ids);
        cleanRedis("dish_*");//清楚菜品缓存
        return Result.success();
    }
    @PutMapping
    @ApiOperation("修改商品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        dishService.updateDish(dishDTO);
        cleanRedis("dish_*");//清楚菜品缓存
        return Result.success();
    }
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishDTO>> list(Long categoryId){
        List<DishDTO> dishDTOList = dishService.list(categoryId);
        return Result.success(dishDTOList);
    }
    //清楚Redis缓存
    private void cleanRedis(String key){
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
